<!--
 * @Author: Dorange.Wang
 * @Date: 2021-03-31 15:57:59
 * @LastEditors: wangming
 * @LastEditTime: 2021-12-06 16:21:04
 * @Description: file content
-->
<route>
{
  "meta":{
    "title":"状态机",
    "showMenu":true,
    "serialNum": 31
  }
}
</route>

<template>
  <div>
    <el-row :gutter="12">
      <el-col :span="6">
        <el-autocomplete
          popper-class="autocomplete--custom"
          style="width: 100%"
          :fetch-suggestions="loadProcessList"
          placeholder="状态机key或者名称搜索"
          @select="handleProcessSelect"
          :debounce="500"
          prefix-icon="el-icon-search"
          :maxlength="64"
          v-model="searchKey"
        >
          <template slot-scope="{ item }">
            <div class="header">{{ item.name }}</div>
            <span class="footer">{{ item.key }}</span>
          </template>
        </el-autocomplete>
      </el-col>
      <el-col v-if="isDesigner" :span="24" class="mt10">
        <DropdownButtons
          :buttons="[
            {
              icon: 'el-icon-circle-plus-outline',
              command: 'process',
              title: '新建状态机',
            },
            {
              icon: 'el-icon-upload2',
              command: 'importProcess',
              title: '导入状态机',
              upload: {
                accept: '.hm_statemodel',
                httpRequest: handleHttpRequest,
              },
            },
            ...(isDefault
              ? [
                  {
                    icon: 'el-icon-folder-add',
                    command: 'folder',
                    title: '新建文件夹',
                  },
                ]
              : []),
          ]"
          @command="handleCreate"
        />
      </el-col>
    </el-row>

    <template v-if="folderData && folderData.length > 0 && isDefault">
      <div class="mt10" style="height: 1px"></div>
      <el-divider content-position="left">状态机管理</el-divider>
      <el-row :gutter="12">
        <el-col :span="6" v-for="folder in folderData" :key="folder.id">
          <el-card class="folder-card mb10" shadow="hover">
            <div class="folder-content" @click="handleFolderClick(folder)">
              <i class="el-icon-folder"></i>
              <span :title="folder.name" class="folder-title">{{
                folder.name
              }}</span>
            </div>
            <el-dropdown
              v-if="isDesigner"
              class="menu"
              placement="bottom"
              trigger="click"
              size="medium"
              @command="handleFolderCommand($event, folder)"
            >
              <i class="el-icon-more"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <div class="mt10" style="height: 1px"></div>
    <el-divider v-if="isDefault" content-position="left"
      >默认（{{ total }}）</el-divider
    >
    <el-divider v-else content-position="left">
      <span class="root-link" @click="loadAllData">状态机管理</span>
      <i class="el-icon-arrow-right"></i>
      {{ currentFolder.name }}
    </el-divider>
    <el-table
      class="mt10"
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      current-row-key="id"
      stripe
      border
    >
      <el-table-column prop="key" label="状态机key" />
      <el-table-column prop="name" label="状态机名称" />
      <el-table-column prop="version" label="已激活版本" width="120">
        <template slot-scope="scope">
          {{ scope.row.version | version
          }}{{ scope.row.published ? "【已发布】" : "" }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="modelName" label="关联业务模型"/> -->
      <el-table-column prop="description" label="状态机描述" />
      <el-table-column prop="modifyDate" label="更新时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.modifyDate | moment }}
        </template>
      </el-table-column>
      <el-table-column prop="actions" label="操作" width="280">
        <template slot-scope="scope">
          <template v-if="isDesigner">
            <span class="table-actionItem">
              <el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button>
            </span>
            <span class="table-actionItem">
              <el-button type="text" @click="handleProcessCommand('design',scope.row)"
              >设计</el-button>
            </span>
            <span class="table-actionItem">
              <el-button type="text" @click="handleExport(scope.row)">导出</el-button>
            </span>
            <span class="table-actionItem">
              <el-button type="text" @click="handleProcessCommand('copy',scope.row)">复制</el-button>
            </span>
            <span class="table-actionItem">
              <el-popconfirm
                title="确定要删除该状态机吗？"
                placement="top"
                @confirm="handleDelete(scope.row)"
              >
                <el-button class="link-danger" type="text" slot="reference">删除</el-button>
              </el-popconfirm>
            </span>

            <span class="table-actionItem">
              <el-dropdown
                @command="handleProcessCommand($event, scope.row)"
                trigger="click"
                placement="bottom"
                size="medium"
              >
                <el-button type="text"
                >更多<i class="el-icon-arrow-down el-icon--right"></i
                ></el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="move">移动</el-dropdown-item>
                  <el-dropdown-item command="version"
                  >新建版本</el-dropdown-item
                  >
                  <el-dropdown-item command="history"
                  >所有版本</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </template>
          <template v-else>
            <span class="table-actionItem">
              <el-button type="text" @click="handleDesign(scope.row)"
                >设计</el-button
              >
            </span>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="tr mt24">
      <x-pagination
        :total="total"
        :pageSize.sync="pageData.pageSize"
        :pageNo.sync="pageData.pageNo"
        @search="loadData"
      />
    </div>
  </div>
</template>

<script>
import ProcessForm from "./__components__/processForm";
import FolderForm from "./__components__/folderForm";
import MoveForm from "./__components__/moveForm";
import HistoryModal from "./__components__/historyModal";
import { genAppDataPrefix, downloadFileStream } from "@/utils/util";
import DropdownButtons from "@/components/DropdownButtons/Index.vue";
import {
  getHmstatemodelfolderPageList,
  deleteHmstatemodelfolder,
} from "@/apis/paas/HmStateModelFolderController.js";
import {
  getHmstatemodelPageList,
  deleteHmstatemodel,
  getHmstatemodelExportByKey,
  postHmstatemodelImportByFolderId,
} from "@/apis/paas/HmStateModelController.js";

const DEFAULT_FOLDER = 1;

export default {
  name: "StateModel",
  components: {
    DropdownButtons,
  },
  data() {
    return {
      searchKey: "",
      loading: false,
      queryData: {},
      pageData: {
        pageSize: 10,
        pageNo: 1,
      },
      tableData: [],
      total: 0,
      folderData: [],
      DEFAULT_FOLDER,
      currentFolder: {
        id: DEFAULT_FOLDER,
      },
      restaurants: [],
    };
  },

  computed: {
    isDefault() {
      return this.currentFolder.id === DEFAULT_FOLDER;
    },
    isDesigner() {
      return process.env.VUE_APP_USER === "ADMIN";
    },
  },

  created() {
    this.loadData();
    this.loadFolderData();
  },

  methods: {
    handleCreate(command) {
      if (command === "process") {
        ProcessForm.addForm({
          folderId: this.currentFolder.id,
        }).then(async (res) => {
          this.$message.success("新增成功");
          await this.loadData();
          this.handleDesign(res);
        });
      } else if (command === "folder") {
        FolderForm.addForm().then(() => {
          this.$message.success("新增成功");
          this.loadFolderData();
        });
      }
    },

    async loadData() {
      this.loading = true;
      return getHmstatemodelPageList({
        ...this.queryData,
        ...this.pageData,
        folderId: this.currentFolder.id,
      })
        .then((res) => {
          this.tableData = res.data;
          this.total = res.totalCount;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    loadFolderData() {
      getHmstatemodelfolderPageList({
        pageSize: 10000,
        pageNo: 1,
      }).then((res) => {
        this._folderData = res.data;
        this.folderData = res.data.filter((item) => item.id !== DEFAULT_FOLDER);
      });
    },

    handleEdit(record) {
      ProcessForm.editForm(record).then(() => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },

    handleDelete(record) {
      deleteHmstatemodel([record.id]).then((res) => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },

    handleDesign(record) {
      const { origin, pathname } = window.location;
      const { id, key, name } = record;
      window.open(
        `${origin}${pathname}#/stateDesign?id=${id}&key=${key}&name=${name}`
      );
    },

    handleProcessCommand(command, record) {
      if (command === "design") {
        this.handleDesign(record);
      } else if (command === "copy") {
        const { id, key, name, description } = record;
        const newRecord = {
          key: key + "_copy",
          name: name + "_copy",
          description,
          sourceId: id,
        };
        ProcessForm.copyForm(newRecord).then((res) => {
          this.loadData();
          if (res && res.id) {
            this.handleDesign({ ...newRecord, id: res.id });
          }
          this.$message.success("操作成功");
        });
      } else if (command === "move") {
        MoveForm.editForm(record, {
          folderList: this._folderData,
        }).then(() => {
          this.loadData();
          this.$message.success("操作成功");
        });
      } else if (command === "version") {
        ProcessForm.verForm({
          ...record,
          sourceId: record.id,
        }).then(() => {
          // 新建版本不需要重新加载
          // this.loadData()
          this.$message.success("新增成功");
        });
      } else if (command === "history") {
        HistoryModal.viewForm(record).then(() => {
          this.loadData();
        });
      }
    },

    handleFolderEdit(record) {
      FolderForm.editForm(record).then(() => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },

    handleFolderCommand(command, record) {
      if (command === "edit") {
        this.handleFolderEdit(record);
      } else if (command === "delete") {
        this.handleFolderDelete(record);
      }
    },

    handleFolderDelete(record) {
      deleteHmstatemodelfolder([record.id]).then((res) => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },

    handleFolderClick(folder) {
      this.currentFolder = folder;
      this.loadData();
    },

    loadAllData() {
      this.currentFolder = {
        id: DEFAULT_FOLDER,
      };
      this.loadData();
    },

    loadProcessList(query = "", callback) {
      const emptyData = [];
      const searchKey = query.trim();
      if (!query.trim()) {
        callback(emptyData);
        return;
      }
      getHmstatemodelPageList({
        pageSize: 5,
        pageNo: 1,
        searchKey,
      }).then((res) => {
        callback(res.data);
      });
    },

    handleProcessSelect(item) {
      this.handleDesign(item);
    },

    /**
     * 导出
     * @param {*} record
     */
    async handleExport(record) {
      const res = await getHmstatemodelExportByKey(
        {
          key: record.key,
        },
        {
          responseType: "blob",
        }
      );
      const fileName = genAppDataPrefix({
        key: record.key,
        ext: "hm_statemodel",
      });
      downloadFileStream(res.data, fileName);
      this.$message.success("导出成功");
    },

    /**
     * 导入
     * @param {*} file
     */
    async handleHttpRequest(file) {
      const formData = new FormData();
      formData.append("multipartFile", file.file);
      await postHmstatemodelImportByFolderId(formData, {
        folderId: this.currentFolder.id,
      });
      this.$message.success("导入成功");
      this.loadData(1);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dropdown-menu {
  min-width: 100px;
}

.folder-card {
  border: 1px solid #dcdfe6;
  position: relative;
  cursor: pointer;

  ::v-deep .el-card__body {
    padding: 0;

    .folder-content {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      padding: 20px;
      box-sizing: border-box;
    }

    .menu {
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .el-icon-folder {
      font-size: 38px;
      color: #999;
      margin-right: 10px;
    }

    .el-icon-more {
      font-size: 18px;
      color: #999;
    }

    .folder-title {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}

.root-link {
  color: #409eff;
  cursor: pointer;
  margin-right: 5px;
  font-weight: bold;
}
</style>
